SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[SaveReportingPeriod]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[SaveReportingPeriod]
GO

  
/***************************************************************************  
* Name:   SaveReportingPeriod
* Purpose:  Save a Reporting Period
*  
* PARAMETERS  
* Name     Description       
* -------------    -----------------------------------------------------------  
* @reportingPeriod 
***************************************************************************/  
CREATE PROCEDURE [dbo].[SaveReportingPeriod] (  
@id INT =  0,
@reportingPeriod VARCHAR(128),
@COITypeId INT = 1
)  
AS  
BEGIN  

	DECLARE @ReportingPeriodYear VARCHAR(4)
	DECLARE @ReportingPeriodId INT
	DECLARE @ReportingPeriodRTU VARCHAR(100)
	SET @ReportingPeriodRTU = 'Real time updates '
	
	IF @id = 0  
	BEGIN  
		INSERT INTO COIReportingPeriods( ReportingPeriod, COITypeId  
		)  
		VALUES  
		( @reportingPeriod  ,@COITypeId
		)  
		IF @@ERROR <> 0 GOTO ERROR_HANDLER  
		SET @ReportingPeriodId = SCOPE_IDENTITY()
		SET @ReportingPeriodYear = RIGHT(LTRIM(RTRIM(@reportingPeriod)),4)
		IF (ISNUMERIC(@ReportingPeriodYear) = 1)
		BEGIN
			SET @ReportingPeriodYear = @ReportingPeriodYear + 1
			SET @ReportingPeriodRTU = @ReportingPeriodRTU + CAST(@ReportingPeriodYear AS VARCHAR(4))
			INSERT INTO COIReportingPeriods(ReportingPeriod, COITypeId)  
			VALUES(@ReportingPeriodRTU,2)  
		END	
		SELECT @ReportingPeriodId 		
		RETURN   
	END  
	ELSE  
	BEGIN  
		UPDATE COIReportingPeriods
		SET  
		ReportingPeriod = @reportingPeriod
		WHERE [Id] = @id  
		IF @@ERROR <> 0 GOTO ERROR_HANDLER  
		SELECT @id   
		RETURN  
	END  
	ERROR_HANDLER:  
	IF @@ERROR <> 0   
	BEGIN  
		RAISERROR('Unable to Save COI Reporting Period', 16, 1)  
		RETURN  
	END  
END  

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO